package com.gitee.shigen.generator.service;

import com.gitee.shigen.generator.mapper.GeneratorMapper;
import com.gitee.shigen.generator.utils.GeneratorUtils;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;
import javax.annotation.Resource;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

/**
 * @author shigenfu
 */
@Service
public class GeneratorService {

    @Resource
    private GeneratorMapper generatorMapper;

    public List<Map<String, Object>> queryList(Map<String, Object> query) {
        return generatorMapper.queryList(query);
    }

    public int queryTotal(Map<String, Object> map) {
        return generatorMapper.queryTotal(map);
    }

    public Map<String, String> queryTable(String tableName) {
        return generatorMapper.queryTable(tableName);
    }

    public List<Map<String, String>> queryColumns(String tableName) {
        return generatorMapper.queryColumns(tableName);
    }

    /**
     * @param tableNames  表名数组
     * @param path        包名 com.gitee.shigen
     * @param mainModule  模块名
     * @param author      作者
     * @param tablePrefix 表前缀，配置文件配置优先
     * @return 字节输出
     */
    public byte[] generatorCode(String[] tableNames, String path, String mainModule, String author, String tablePrefix) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        // todo 优化数据库的查询
        for (String tableName : tableNames) {
            // 查询表信息
            Map<String, String> table = queryTable(tableName);
            // 查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            // 生成代码
            GeneratorUtils.generateCode(table, columns, zip, author, path, mainModule, tablePrefix);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
}
